package com.huiyujinrong.qiangdanbao.activity.my;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;
import com.huiyujinrong.qiangdanbao.R;
import com.huiyujinrong.qiangdanbao.network.Api;
import com.huiyujinrong.qiangdanbao.permission.PermissionSupport;
import com.huiyujinrong.qiangdanbao.utils.JuCircle;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 身份证明
 * 2017/4/12
 * yd
 */
public class UserWork extends PermissionSupport {


    @BindView(R.id.toolbar_Title)
    TextView title;
    @BindView(R.id.toolbar_Back)
    RelativeLayout back;

    @BindView(R.id.works_gongpai)
    SimpleDraweeView works_gongpai;
    @BindView(R.id.works_mingpian)
    SimpleDraweeView works_mingpian;
    private ProgressDialog progressDialog;


    private int inFor;

    String bussiness;
    String work;
    private boolean is2Setting;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.works);
        ButterKnife.bind(this);
        setToolbar();
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        bussiness = getIntent().getStringExtra("bussiness");
        work = getIntent().getStringExtra("work");

        setImage();
        if (!TextUtils.isEmpty(work)) {
            Picasso.with(this)
                    .load(work)
                    .fit()
                    .transform(new JuCircle())
                    .into(works_gongpai);
        }
        if (!TextUtils.isEmpty(bussiness)) {
            Picasso.with(this)
                    .load(bussiness)
                    .fit()
                    .transform(new JuCircle())
                    .into(works_mingpian);
        }
    }


    //设置 toolbar
    private void setToolbar() {
        back.setVisibility(View.VISIBLE);
        title.setText(R.string.works);
    }

    private void setImage() {
        if (Api.getWork_gongpai() != null) {
            Bitmap gongpai = getBitmap4File(works_gongpai, Api.getWork_gongpai());
            works_gongpai.setBackground(new BitmapDrawable(gongpai));
            works_gongpai.setImageBitmap(null);
            setFillet(works_gongpai);
        }

        if (Api.getWork_mingpian() != null) {
            Bitmap mingpian = getBitmap4File(works_gongpai, Api.getWork_mingpian());
            works_mingpian.setBackground(new BitmapDrawable(mingpian));
            works_mingpian.setImageBitmap(null);
            setFillet(works_mingpian);
        }
    }

    @OnClick({R.id.toolbar_Back, R.id.select_gongpai, R.id.select_mingpian, R.id.works_gongpai, R.id.works_mingpian})
    void onClicks(View view) {
        switch (view.getId()) {
            case R.id.toolbar_Back:
                finish();
                break;
            case R.id.select_gongpai:
                new AlertDialog.Builder(this)
                        .setView(R.layout.works_gongpai)
                        .show();
                break;
            case R.id.select_mingpian:
                new AlertDialog.Builder(this)
                        .setView(R.layout.works_mingpian)
                        .show();
                break;
            case R.id.works_gongpai:
                inFor = 0;
                requestPermissions();
                break;
            case R.id.works_mingpian:
                inFor = 1;
                requestPermissions();
                break;
        }
    }

    private void  requestPermissions(){
        doRequestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 8, listener);
    }
    PermissionListener listener = new PermissionListener() {
        @Override
        public void onPermissionsGranted(int requestCode) {
            getShowDialog();
        }

        @Override
        public void onPermissionsDenied(int requestCode) {
            showTipsDialog();
        }
    };

    //显示所有提示对话框
    private void showTipsDialog() {
        new android.app.AlertDialog.Builder(this)
                .setTitle("授权提示：")
                .setMessage("应用缺少必要权限,无法使用部分功能。是否去设置?")
                .setNegativeButton("不设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        finish();
                    }
                })
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        is2Setting = true;
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivity(intent);
                    }
                }).show();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(is2Setting){
            is2Setting=false;
            requestPermissions();
        }
    }



    //保存
    @OnClick(R.id.work_save)
    void workSave() {
        if (Api.getWork_gongpai() != null || Api.getWork_mingpian() != null) {
            finish();
        } else {
            Toast.makeText(this, "请上传工牌或名片", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 选择 上传身份证照片
     * 相机  or  手机相册
     */
    private void getShowDialog() {
        final String items[] = {"相机", "从手机相册选择"};
        new AlertDialog.Builder(this)
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                //照相
                                callSysCamera();
                                break;
                            case 1:
                                //相册
                                callSysAlbum();
                                break;
                            default:
                        }
                    }
                }).show();
    }

    //打开相机
    private void callSysCamera() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
        startActivityForResult(intent, 0);
    }

    //打开相册
    private void callSysAlbum() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, 1);
    }

    //回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String path = images.get(0).path;
                getPDialog();
                getLuBan(new File(path));
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void getPDialog() {
        progressDialog.setMessage("正在加载图片...");
        progressDialog.show();
    }

    private void getLuBan(File imageFile) {
        Luban.with(this)
                .load(imageFile)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        progressDialog.dismiss();
                        if (inFor == 0) {
                            Bitmap bt = getBitmap4File(works_gongpai, file);
                            Api.setWork_gongpai(file);
                            works_gongpai.setBackground(new BitmapDrawable(bt));
                            works_gongpai.setImageBitmap(null);
                            setFillet(works_gongpai);
                        } else if (inFor == 1) {
                            Bitmap bt = getBitmap4File(works_mingpian, file);
                            Api.setWork_mingpian(file);
                            works_mingpian.setBackground(new BitmapDrawable(bt));
                            works_mingpian.setImageBitmap(null);
                            setFillet(works_mingpian);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过去出现问题时调用
                        progressDialog.dismiss();
                    }
                }).launch();//启动压缩
    }

    //获取本地文件中的Bitmap图像源
    private Bitmap getBitmap4File(ImageView imageView, File imageFile) {
        int imageViewWidth = imageView.getWidth();
        int imageViewHeight = imageView.getHeight();
        BitmapFactory.Options opts = new BitmapFactory.Options();
        //设置这个，只得到Bitmap的属性信息放入opts，而不把Bitmap加载到内存中
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imageFile.getPath(), opts);
        int bitmapWidth = opts.outWidth;
        int bitmapHeight = opts.outHeight;
        int scale = Math.min(imageViewWidth / bitmapWidth, imageViewHeight / bitmapHeight);
        opts.inSampleSize = scale;
        //内存不足时可被回收
        opts.inPurgeable = true;
        opts.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath(), opts);
        return bitmap;
    }

    /**
     * 设置圆角
     *
     * @param view
     */
    private void setFillet(SimpleDraweeView view) {
        RoundingParams roundingParams = RoundingParams.fromCornersRadius(20f);
        roundingParams.setOverlayColor(getResources().getColor(R.color.baise));
        GenericDraweeHierarchy hierarchy = GenericDraweeHierarchyBuilder.newInstance(getResources())
                .setRoundingParams(roundingParams)
                .build();
        view.setHierarchy(hierarchy);
    }

}
